import {createSlice} from "@reduxjs/toolkit";
import {useSelector} from "react-redux";
import {addWeibo, deleteWeibo, getWeibo, putWeibo} from "../../api/weibo";

const weiboSlice = createSlice({
    name:'weibo',
    initialState:{
        contentList:[],
        pageNo:1,
        pageSum:1,
        pageSize:5
    },
    reducers:{
        upWeiboState(state,{payload}){
            state.contentList = payload.contentList
            state.pageNo = payload.pageNo
            state.pageSum = payload.pageSum
            state.pageSize = payload.pageSize
        }
    }
})
export const {upWeiboState} = weiboSlice.actions
export const useGetSelectors = ()=>{
    return useSelector(state=>state.weibo)
}
//获取微博内容
export const getWeiboAsync = (pageNo,pageSize)=>{
    return async (dispatch,getstate)=>{
        if(!pageNo) pageNo = getstate().weibo.pageNo
        if(!pageSize) pageSize = getstate().weibo.pageSize
        const res = await getWeibo(pageNo,pageSize)
        dispatch(upWeiboState({...res,pageSize}))
    }
}

//添加微博
export const addWeiboAsync = (contentRef)=>{
    return async (dispatch)=>{
        const content = contentRef.current.value.trim()
        if(!content)return alert('请输入微博内容！')
        await addWeibo(content)
        contentRef.current.value = ''
        dispatch(getWeiboAsync())
    }
}

//删除微博
export const deleteWeiboAsync = (id)=>{
    return async (dispatch)=>{
        await deleteWeibo(id)
        dispatch(getWeiboAsync())
    }
}

//修改微博
export const putWeiboAsync = (id,type)=>{
    return async (dispatch)=>{
        await putWeibo(id,type)
        dispatch(getWeiboAsync())
    }
}
export default weiboSlice.reducer